package com.ms.content.controller;

import java.io.IOException;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.ms.content.dao.BargainingItemDao;
import com.ms.content.entity.BargainingItemEntity;
import com.ms.content.entity.GoodsEntity;
import com.ms.content.service.AdmsService;
import com.ms.content.service.GoodsService;
import com.ms.content.util.MyRedissonConfig;
import net.sf.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayOpenPublicTemplateMessageIndustryModifyRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayOpenPublicTemplateMessageIndustryModifyResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ms.content.dao.MiaoshaActivityDao;
import com.ms.content.dao.OrderInfoDao;
import com.ms.content.entity.MiaoshaActivityEntity;
import com.ms.content.util.AlipayConfig;
import org.jdom2.JDOMException;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.ms.content.entity.OrderInfoEntity;
import com.ms.content.service.OrderInfoService;
import com.ms.common.utils.PageUtils;
import com.ms.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 这个是商品秒杀表
 *
 * @author wc
 * @email sunlightcs@gmail.com
 * @date 2022-02-22 11:56:10
 */
@Controller
@RequestMapping("content/orderinfo")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;


    @Autowired
    private OrderInfoDao orderInfoDao;

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private AdmsService admsService;

    @Autowired
    private MiaoshaActivityDao miaoshaActivityDao;

    @Autowired
    private BargainingItemDao bargainingItemDao;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = orderInfoService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 退款
     *
     * @param
     * @return
     * @throws Exception * 支付宝的退款接口
     *                   * @param orderId 商户的订单号
     *                   * @param tradeNo 支付宝的交易流水号
     *                   * @param totalAmount 退款金额
     *                   * @return
     */
    //1.
    @RequestMapping(value = "/tuihuan")
    public R alipayCreateOrderRefund(@RequestParam String orderId, @RequestParam String tradeNo, @RequestParam String totalAmount) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", "GBK", AlipayConfig.alipay_public_key, "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("refund_amount", totalAmount);
        bizContent.put("out_request_no", orderId);

//// 返回参数选项，按需传入
//JSONArray queryOptions = new JSONArray();
//queryOptions.add("refund_detail_item_list");
//bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return R.ok();
        } else {
            System.out.println("调用失败");
            return R.error();
        }
    }
//2.
//    @RequestMapping(value = "/tuihuan")
//    public R alipayCreateOrderRefund(@RequestParam String orderId,@RequestParam String tradeNo,@RequestParam String totalAmount) {
//     //   Map map = new LinkedHashMap();
////        String orderId="0740582c-d947-43e7-a9d3-341be6cb205d";
////        String tradeNo="2022022622001480581434940708";  //
////        String totalAmount="0.01";
//        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig. gatewayUrl,
//                AlipayConfig.app_id, AlipayConfig.merchant_private_key,
//                "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, "RSA2");
//        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//
//        AlipayTradeRefundModel model= new AlipayTradeRefundModel();
//        model.setOutTradeNo(orderId);//订单支付时传入的商户订单号
//        model.setTradeNo(tradeNo);//支付宝交易号
//        model.setRefundAmount(totalAmount);//refund_amount    需要退款的金额，该金额不能大于订单金额,单位为元
//
//        request.setBizModel(model);//请求参数
//
//        AlipayTradeRefundResponse response=null;
//        try {
//            response = alipayClient.execute(request);
//
//            System.out.println(JSONObject.fromObject(response).toString());
//    //        Map tuiMap=JSONObject.fromObject(response);
//
//        }catch ( AlipayApiException e){
//            String massage = "alipay.trade.refund退款接口：订单签名错误";
//            System.out.println(massage);
//        }
//        return  R.ok();
//        if(response.isSuccess()){
//            System.out.println("调用成功");
//            map.put("status", 0);//订单退款  status：0 成功 1:失败
//            System.out.println("支付宝：支付订单支付结果查询：订单out_trade_no----"+orderId+"---订单退款成功！");
//        } else {
//            System.out.println("调用失败");
//            map.put("status",1);//订单退款  status：0 成功 1:失败
//            System.out.println("支付宝：支付订单支付结果查询：订单out_trade_no----"+orderId+"---订单退款失败！");
//        }
//        return R.ok().put("map",map);
//    }


    @RequestMapping(value = "/huidiao")
    public String execute(HttpServletRequest request) throws Exception {
//获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

//        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

//        //实例化客户端
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id,AlipayConfig.merchant_private_key, "json",AlipayConfig.charset,AlipayConfig.alipay_public_key, "RSA2");
////实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.open.public.template.message.industry.modify
//        AlipayOpenPublicTemplateMessageIndustryModifyRequest requestt = new AlipayOpenPublicTemplateMessageIndustryModifyRequest();
////SDK已经封装掉了公共参数，这里只需要传入业务参数
////此次只是参数展示，未进行字符串转义，实际情况下请转义
//        requestt.setBizContent("  {" +
//                "    \"primary_industry_name\":\"IT科技/IT软件与服务\"," +
//                "    \"primary_industry_code\":\"10001/20102\"," +
//                "    \"secondary_industry_code\":\"10001/20102\"," +
//                "    \"secondary_industry_name\":\"IT科技/IT软件与服务\"" +
//                " }");
//        AlipayOpenPublicTemplateMessageIndustryModifyResponse response = alipayClient.execute(requestt);
////调用成功，则处理业务逻辑
//        if(response.isSuccess()){
//        if (signVerified){
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

        //付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

        System.out.println("trade_no:" + trade_no + "out_trade_no:" + out_trade_no + "total_amount:" + total_amount);
        OrderInfoEntity orderInfoEntity = orderInfoDao.selectOne(new QueryWrapper<OrderInfoEntity>().eq("id", out_trade_no));
        if (orderInfoEntity != null) {
            orderInfoEntity.setStatus(1);
            orderInfoEntity.setPayDate(new Date());
            orderInfoDao.updateById(orderInfoEntity);
            return "redirect:http://127.0.0.1:5500/activity.html";
        }
//        }
        //——请在这里编写您的程序（以下代码仅作参考）——
//        if(signVerified) {

        return "error";
        //out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
//        }else {
//            System.out.println("验签失败");
//            return "error";
//        }
    }

    @RequestMapping(value = "/huidiaoKj")
    public String executekj(HttpServletRequest request) throws Exception {
//获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

//        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

//        //实例化客户端
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id,AlipayConfig.merchant_private_key, "json",AlipayConfig.charset,AlipayConfig.alipay_public_key, "RSA2");
////实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.open.public.template.message.industry.modify
//        AlipayOpenPublicTemplateMessageIndustryModifyRequest requestt = new AlipayOpenPublicTemplateMessageIndustryModifyRequest();
////SDK已经封装掉了公共参数，这里只需要传入业务参数
////此次只是参数展示，未进行字符串转义，实际情况下请转义
//        requestt.setBizContent("  {" +
//                "    \"primary_industry_name\":\"IT科技/IT软件与服务\"," +
//                "    \"primary_industry_code\":\"10001/20102\"," +
//                "    \"secondary_industry_code\":\"10001/20102\"," +
//                "    \"secondary_industry_name\":\"IT科技/IT软件与服务\"" +
//                " }");
//        AlipayOpenPublicTemplateMessageIndustryModifyResponse response = alipayClient.execute(requestt);
////调用成功，则处理业务逻辑
//        if(response.isSuccess()){
//        if (signVerified){
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

        //付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

        System.out.println("trade_no:" + trade_no + "out_trade_no:" + out_trade_no + "total_amount:" + total_amount);
        BargainingItemEntity bargainingItemEntity = bargainingItemDao.selectOne(new QueryWrapper<BargainingItemEntity>().eq("id", out_trade_no));
        if (bargainingItemEntity != null) {
            bargainingItemEntity.setGoodsUserStatic(2);
            bargainingItemEntity.setXgTime(new Date());
            bargainingItemDao.updateById(bargainingItemEntity);
            return "redirect:http://127.0.0.1:5500/activity.html";
        }
//        }
        //——请在这里编写您的程序（以下代码仅作参考）——
//        if(signVerified) {

        return "error";
        //out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
//        }else {
//            System.out.println("验签失败");
//            return "error";
//        }
    }


    /**
     * 秒杀商品
     * 查询商品信息 并添加到商品订单  之后进行点击订单支付状态  可以立即支付
     */
    @RequestMapping("/order")
    @ResponseBody
    public R order(@RequestParam Integer fid, @RequestParam Integer id, @RequestParam String uid, @RequestParam Integer sid, @RequestParam String path) throws InterruptedException {

        R r = orderInfoService.ms(fid, id, uid, sid,path);
        return r;
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") Long id) {
        OrderInfoEntity orderInfo = orderInfoService.getById(id);

        return R.ok().put("orderInfo", orderInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody OrderInfoEntity orderInfo) {
        orderInfoService.save(orderInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public R update(@RequestBody OrderInfoEntity orderInfo) {
        orderInfoService.updateById(orderInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody Long[] ids) {
        orderInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
